import { useRef, RefObject, useState, useEffect } from 'react';
import { Modal, Form, message, Select, Input, Switch, FormInstance } from 'antd';
import { VideoCourtSchema, VideoPartySchema } from '@src/components/schema/videoCourt';
import { CaseSchema, PartySchema } from '@src/components/schema/caseSchema';
import { ArbitratorSchema } from '@src/components/schema/arbitrator';
import { getArbitratorsRequest } from './ajax'
import { awaitWrap } from '@js/tool';
import { addPersonRequest, updatePersonRequest, getParticipantListRequest } from './ajax'
import { ParticipantSchema } from '@src/components/schema/videoCourt';

const { Item } = Form
const { Option } = Select
const types = ['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员', '仲裁秘书', '速录员', '其他']

function onFinish (d: { [k: string]: any }, refreshFn: () => void, hide: () => void) {
  d.iscompere = d.iscompere ? 1 : 0
  const id = d.id
  if (d.license !== undefined) {
    d.license_type = '身份证'
  }
  if (id) {
    delete d.id
    updateHandle(id, d, refreshFn, hide)
  } else {
    addHandle(d, refreshFn, hide)
  }
}

async function addHandle (data: { [k: string]: any }, refreshFn: () => void, h: () => void) {
  const hide = message.loading('提交中')
  const [e] = await awaitWrap(addPersonRequest(data))
  hide()
  if (e === null) {
    message.success('新增成功')
    h()
    refreshFn()
  }
}

async function updateHandle (id: string, data: { [k: string]: any }, refreshFn: () => void, h: () => void) {
  const hide = message.loading('提交中')
  const [e] = await awaitWrap(updatePersonRequest(id, data))
  hide()
  if (e === null) {
    message.success('修改成功')
    h()
    refreshFn()
  }
}

async function initArbitrators (caseid: string, setArbitartors: (v: ArbitratorSchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getArbitratorsRequest(caseid))
  if (e === null && d !== null) {
    setArbitartors(d)
  }
}

async function getParticipant (caseid: string, setOtherPersonList: (v: ParticipantSchema[]) => void) {
  const [e, d] = await awaitWrap(getParticipantListRequest(caseid))
  if (e === null && d !== null) {
    setOtherPersonList(d)
  }
}

// 改变仲裁地位
function changeType (
  v: string,
  formRef: RefObject<FormInstance>,
  meetingid: string,
  hearingroomid: string,
  meetingData: VideoCourtSchema,
  data: CaseSchema,
  arbitrators: ArbitratorSchema[],
  otherPersonList: ParticipantSchema[],
  setPersonList: (v: VideoPartySchema[]) => void,
  setType: (v: string) => void
) {
  const c = formRef.current
  if (!c) {
    return undefined
  }
  c.resetFields()
  c.setFieldsValue({
    type: v,
    meetingid,
    hearingroomid
  })
  let personList: VideoPartySchema[] = []
  if (v === '申请人') {
    personList = data.applicants.filter(li => li.status && li.subject_type === '自然人')
  } else if (v === '被申请人') {
    personList = data.respondents.filter(li => li.status && li.subject_type === '自然人')
  } else if (v === '申请人代理人') {
    personList = data.applicant_agents || []
  } else if (v === '被申请人代理人') {
    personList = data.respondents_agents || []
  } else if (v === '仲裁员') {
    personList = arbitrators as unknown as VideoPartySchema[]
  } else if (v === '速录员') {
    personList = []
    if (meetingData.recorder && meetingData.recorderid && meetingData.recorder_mobile) {
      personList.push({ id: meetingData.recorderid, name: meetingData.recorder, mobile: meetingData.recorder_mobile } as VideoPartySchema)
    }
  } else if (v === '仲裁秘书') {
    initFormByPerson(v, {id: data.processerid, name: data.processer, mobile: data.processer_mobile}, formRef)
  } else {
    personList = otherPersonList as unknown as VideoPartySchema[]
  }
  setPersonList(personList)
  setType(v)
}

// 根据人员信息初始化表单数据
function initFormByPerson (t: string, d: {[k: string]: any}, formRef: RefObject<FormInstance>) {
  const c = formRef.current
  const form: {[k: string]: any} = { name: d.name, mobile: d.mobile || '', biz_uid: d.id }
  if (['申请人代理人', '被申请人代理人'].indexOf(t) !== -1) {
    const p: VideoPartySchema[] = d.party || []
    form.partyid = p.map(li => li.partyid).join()
  }
  if (c) {
    c.setFieldsValue(form)
  }
}

// 选择人员
function changeName (t: string, id: string, l: PartySchema[], formRef: RefObject<FormInstance>) {
  let o = null
  for (let i = 0; i < l.length; i++) {
    if (l[i].id === id) {
      o = l[i]
      break
    }
  }
  if (!o) {
    return false
  }
  initFormByPerson(t, o, formRef)
}

// 渲染姓名项
function renderNameItem (t: string, personList: VideoPartySchema[], formRef: RefObject<FormInstance>) {
  const p = personList
  if (['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员', '速录员', '其他'].indexOf(t) !== -1) {
    return (
      <Select placeholder='请选择人员' onChange={v => changeName(t, v, personList, formRef)}>
        {p.map((li, i) => <Option key={i} value={li.id}>{li.name}</Option>)}
      </Select>
    )
  }
  return <Input placeholder='请输入姓名' disabled={t === '仲裁秘书'} />
}

interface Props {
  data: VideoPartySchema | null
  visible: boolean
  caseData: CaseSchema
  hearingroomid: string
  meetingid: string
  meetingData: VideoCourtSchema
  hide: () => void
  refreshFn: () => void
}

function Main ({ data, visible, hide, caseData, meetingData, hearingroomid, meetingid, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  const id = data ? data.id : ''
  const [arbitrators, setArbitrators] = useState<ArbitratorSchema[]>([])
  const [personList, setPersonList] = useState<VideoPartySchema[]>([])
  const [otherPersonList, setOtherPersonList] = useState<ParticipantSchema[]>([])
  const [t, setT] = useState('')
  useEffect(() => {
    if (caseData) {
      initArbitrators(caseData.id, setArbitrators)
      getParticipant(caseData.id, setOtherPersonList)
    }
  }, [caseData])
  useEffect(() => {
    const c = formRef.current
    if (c) {
      if (visible) {
        if (data) {
          c.setFieldsValue(data)
          setT(data.type)
        }
      } else {
        c.resetFields()
      }
    }
  }, [data, visible, formRef])
  return (
    <Modal
      title={id ? '修改参会人' : '新增参会人'}
      visible={visible}
      onOk={() => formRef.current?.submit()}
      onCancel={() => hide()}
    >
      <Form ref={formRef} labelCol={{ flex: '108px' }} onFinish={d => onFinish(d, refreshFn, hide)}>
        <Item name='id' noStyle><span /></Item>
        <Item name='meetingid' noStyle><span /></Item>
        <Item name='hearingroomid' noStyle><span /></Item>
        <Item name='partyid' noStyle><span /></Item>
        <Item name='biz_uid' noStyle><span /></Item>
        <Item name='type' label='仲裁地位' rules={[{ required: true, message: '仲裁地位不能为空' }]}>
          <Select placeholder='请选择仲裁地位' onChange={v => changeType(v, formRef, meetingid, hearingroomid, meetingData, caseData, arbitrators, otherPersonList, setPersonList, setT)}>
            {types.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
          </Select>
        </Item>
        <Item name='name' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
          {renderNameItem(t, personList, formRef)}
        </Item>
        <Item name='mobile' label='手机号' rules={[{ required: true, message: '手机号不能为空' }]}>
          <Input placeholder='请输入手机号' maxLength={11} disabled />
        </Item>
        <Item name='iscompere' label='是否为主持人' valuePropName='checked'>
          <Switch checkedChildren='是' unCheckedChildren='否' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
